package com.wuda.servlet.user;

import com.wuda.bean.User;
import com.wuda.dao.UserDao;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet("/user/updateUsername")
public class UpdateUsername extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf8");
		PrintWriter out = response.getWriter();

		int userId = Integer.parseInt(request.getParameter("userId"));
		String newUsername = request.getParameter("newUsername");

		UserDao userDao = new UserDao();
		boolean success = userDao.updateUsername(userId, newUsername);

		JSONObject jsonResult = new JSONObject();
		if (success) {
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute("user");
			user.setUsername(newUsername);
			session.setAttribute("user", user);

			jsonResult.put("code", 200);
			jsonResult.put("msg", "用户名更新成功");
		} else {
			jsonResult.put("code", 500);
			jsonResult.put("msg", "用户名更新失败");
		}

		out.print(jsonResult);
		out.flush();
	}

}
